package com.alipay.rebate.shop.utils;

import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.RefundOrders;
import com.alipay.rebate.shop.pojo.dingdanxia.DingdanxiaOrder;
import com.alipay.rebate.shop.pojo.dingdanxia.DingdanxiaRsp;
import com.alipay.rebate.shop.pojo.taobao.TkOrderRsponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

public class TestUtil {

  private static Logger logger = LoggerFactory.getLogger(TestUtil.class);

  public static List<RefundOrders> testRefund(){
    BufferedReader inputStream = null;
    try {
      String fileName = "classpath:json4.txt";
      File file =  ResourceUtils.getFile(fileName);
      inputStream = new BufferedReader(new FileReader(file));
      String str = "";
      StringBuilder builder = new StringBuilder();
      while((str = inputStream.readLine()) != null){
        builder.append(str);
      }
      System.out.println(builder.toString());
      Gson gson = new GsonBuilder().create();
      Type type = new TypeToken<List<RefundOrders>>() {}.getType();
      return gson.fromJson(builder.toString(),type);
    } catch (IOException e) {
      e.printStackTrace();
      if(inputStream != null){
        try {
          inputStream.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
    return null;
  }


  public static TkOrderRsponse test(int type){
    BufferedReader inputStream = null;
    try {
      String fileName = "classpath:json" + type + ".txt";
      File file =  ResourceUtils.getFile(fileName);
      inputStream = new BufferedReader(new FileReader(file));
      String str = "";
      StringBuilder builder = new StringBuilder();
      while((str = inputStream.readLine()) != null){
        builder.append(str);
      }
      System.out.println(builder.toString());
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      DingdanxiaRsp<List<DingdanxiaOrder>> dingdanxiaRsp =
          objectMapper.readValue(builder.toString(),new TypeReference<DingdanxiaRsp<List<DingdanxiaOrder>>>(){});
      inputStream.close();
      TkOrderRsponse response = new TkOrderRsponse();
      response.setHas_next(false);
      List<Orders> orders =  convertResponseToOrdersList(dingdanxiaRsp);
      response.setData(orders);
      return response;
    } catch (IOException e) {
      e.printStackTrace();
      if(inputStream != null){
        try {
          inputStream.close();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
    return null;
  }

  private static List<Orders> convertResponseToOrdersList(
      DingdanxiaRsp<List<DingdanxiaOrder>> dingdanxiaRsp){
    logger.debug("dingdanxiaResponse is : {}", dingdanxiaRsp);
    if(dingdanxiaRsp != null){
      List<Orders> list = new ArrayList<>();
      Optional.ofNullable(dingdanxiaRsp.getData()).ifPresent(dingdanxiaOrders -> {
        dingdanxiaOrders.forEach(dingdanxiaOrder -> {
          Orders orders = convertFromDingdanxiaOrderToModelOrder(dingdanxiaOrder);
          list.add(orders);
        });
      });
      return list;
    }
    return null;
  }

  private static Orders convertFromDingdanxiaOrderToModelOrder(
      DingdanxiaOrder dingdanxiaOrder
  ){
    Orders orders = new Orders();
    // trade_parent_id
    orders.setTradeParentId(String.valueOf(dingdanxiaOrder.getTrade_parent_id()));
    // trade_id
    orders.setTradeId(String.valueOf(dingdanxiaOrder.getTrade_id()));
    // num_iid
    orders.setNumIid(dingdanxiaOrder.getNum_iid());
    // item_title
    orders.setItemTitle(dingdanxiaOrder.getItem_title());
    // item_num
    orders.setItemNum(dingdanxiaOrder.getItem_num());
    // price
    if(!StringUtils.isEmpty(dingdanxiaOrder.getPrice())){
      orders.setPrice(new BigDecimal(dingdanxiaOrder.getPrice()).setScale(2));
    }
    // pay_price
    if(!StringUtils.isEmpty(dingdanxiaOrder.getPay_price())){
      orders.setPayPrice(new BigDecimal(dingdanxiaOrder.getPay_price()).setScale(2));
    }
    // seller_nick
    orders.setSellerNick(dingdanxiaOrder.getSeller_nick());
    // seller_shop_title
    orders.setSellerShopTitle(dingdanxiaOrder.getSeller_shop_title());
    // commission
    if(!StringUtils.isEmpty(dingdanxiaOrder.getCommission())){
      orders.setCommission(new BigDecimal(dingdanxiaOrder.getCommission()).setScale(2));
    }
    // commission_rate
    if(!StringUtils.isEmpty(dingdanxiaOrder.getCommission_rate())){
      orders.setCommissionRate(new BigDecimal(dingdanxiaOrder.getCommission_rate()).setScale(2));
    }
    // create_time
    if(!StringUtils.isEmpty(dingdanxiaOrder.getCreate_time())){
      orders.setCreateTime(dingdanxiaOrder.getCreate_time());
    }
    // earning_time
    if(!StringUtils.isEmpty(dingdanxiaOrder.getEarning_time())){
      orders.setEarningTime(dingdanxiaOrder.getEarning_time());
    }
    // tk_status
    orders.setTkStatus(dingdanxiaOrder.getTk_status());
    // tk3rd_type
    orders.setTk3rdType(dingdanxiaOrder.getTk3rd_type());
    // tk3rd_pub_id
    orders.setTk3rdPubId(dingdanxiaOrder.getTk3rd_pub_id());
    // order_type
    orders.setOrderType(dingdanxiaOrder.getOrder_type());
    // income_rate
    if(!StringUtils.isEmpty(dingdanxiaOrder.getIncome_rate())){
      BigDecimal incomeRate = new BigDecimal(dingdanxiaOrder.getIncome_rate());
      orders.setIncomeRate(incomeRate);
    }
    // pub_share_pre_fee
    if(!StringUtils.isEmpty(dingdanxiaOrder.getPub_share_pre_fee())){
      BigDecimal pubSharePreFee = new BigDecimal(dingdanxiaOrder.getPub_share_pre_fee());
      orders.setPubSharePreFee(pubSharePreFee);
    }
    // subsidy_rate
    if(!StringUtils.isEmpty(dingdanxiaOrder.getSubsidy_rate())){
      BigDecimal subsidyRate = new BigDecimal(dingdanxiaOrder.getSubsidy_rate());
      orders.setSubsidyRate(subsidyRate);
    }
    // subsidy_type
    orders.setSubsidyType(dingdanxiaOrder.getSubsidy_type());
    // terminal_type
    orders.setTerminalType(dingdanxiaOrder.getTerminal_type());
    // auction_category
    orders.setAuctionCategory(dingdanxiaOrder.getAuction_category());
    // site_id
    orders.setSiteId(Long.valueOf(dingdanxiaOrder.getSite_id()));
    // site_name
    orders.setSiteName(dingdanxiaOrder.getSite_name());
    // adzone_id
    orders.setAdzoneId(Long.valueOf(dingdanxiaOrder.getAdzone_id()));
    // adzone_name
    orders.setAdzoneName(dingdanxiaOrder.getAdzone_name());
    // alipay_total_price
    if(!StringUtils.isEmpty(dingdanxiaOrder.getAlipay_total_price())){
      BigDecimal alipayTotalPrice = new BigDecimal(dingdanxiaOrder.getAlipay_total_price());
      orders.setAlipayTotalPrice(alipayTotalPrice);
    }
    // total_commission_rate
    if(!StringUtils.isEmpty(dingdanxiaOrder.getTotal_commission_rate())){
      BigDecimal totalCommissionRate = new BigDecimal(dingdanxiaOrder.getTotal_commission_rate());
      orders.setTotalCommissionRate(totalCommissionRate);
    }
    // total_commission_fee
    if(!StringUtils.isEmpty(dingdanxiaOrder.getTotal_commission_fee())){
      BigDecimal totalCommissionFee = new BigDecimal(dingdanxiaOrder.getTotal_commission_fee());
      orders.setTotalCommissionFee(totalCommissionFee);
    }
    // subsidy_fee
    if(!StringUtils.isEmpty(dingdanxiaOrder.getSubsidy_rate())){
      BigDecimal subsidyFee = new BigDecimal(dingdanxiaOrder.getSubsidy_rate());
      orders.setSubsidyFee(subsidyFee);
    }
    // relation_id
    orders.setRelationId(dingdanxiaOrder.getRelation_id());
    // special_id
    orders.setSpecialId(dingdanxiaOrder.getSpecial_id());
    // clickTime
    if(!StringUtils.isEmpty(dingdanxiaOrder.getClick_time())){
      orders.setClickTime(dingdanxiaOrder.getClick_time());
    }

    return orders;
  }

//  public static void main(String[] args) {
//
//
//      StringBuffer buffer=new StringBuffer();
//      try {
//
//
//        String id = "586529711275";
//        String urlTaobao = "https://item.taobao.com/item.htm?id=" + id;
//
////        URL url = new URL("http://tool.manmanbuy.com/history.aspx?DA=1&action=gethistory&" +
////                "url=" + urlTaobao +
////                "&bjid=&spbh=&cxid=&zkid=&w=951&token=egwu9a69a89b9b3742afa518258eb678631c9wrfthc");
//
//        URL url = new URL("https://api.yhmai.cn/router?v=1&api=yhmai.query.history&" +
//                "url="+urlTaobao+"&_t="+id);
//
//        //2.打开http连接
//        HttpURLConnection httpUrlConn=(HttpURLConnection)url.openConnection();
//        httpUrlConn.setDoInput(true);
//        httpUrlConn.setRequestMethod("GET");
//        httpUrlConn.connect();
//
//        //获得输入
//        InputStream inputStream=httpUrlConn.getInputStream();
//        InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"gbk");
//        BufferedReader bufferReader=new BufferedReader(inputStreamReader);
//
//
//        //将bufferReader放入到Buff里面
//        String str=null;
//        while ((str=bufferReader.readLine())!=null) {
//          buffer.append(str);
//        }
//        bufferReader.close();
//        inputStreamReader.close();
//        inputStream.close();
//        inputStream=null;
//        //断开连接
//        httpUrlConn.disconnect();
//      } catch (MalformedURLException e) {
//        // TODO Auto-generated catch block
//        e.printStackTrace();
//      } catch (IOException e) {
//        // TODO Auto-generated catch block
//        e.printStackTrace();
//      }
//
//    System.out.println(buffer.toString());
//
//
//  }
}
